package com.suixun.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.authority.controller.BaseManager;
import com.google.gson.Gson;
import com.suixun.entity.DeviceInfo;
import com.suixun.entity.School;
import com.suixun.entity.form.ParamForm;
import com.suixun.entity.page.PageModel;
import com.suixun.exception.OpServiceException;
import com.suixun.service.DeviceInitService;
import com.suixun.service.SchoolService;
import com.suixun.util.Constant;
import com.suixun.vo.DeviceVO;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/deviceInitManage")
public class DeviceInitManage extends BaseManager {
	@Resource
	private DeviceInitService deviceInitService;
	@Resource
	private SchoolService schoolService;


	/**
	 * 分页查询设备列表
	 * 
	 * @return
	 */

	@RequestMapping(value = "queryDeviceInitList.json")
	@ResponseBody
	public Object queryDeviceInitListPage(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			return success(deviceInitService.queryDeviceInitlistPage(paramForm));
		} catch (Exception e) {
			e.printStackTrace();
			logger("DeviceInitManage queryDeviceInitListPage:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * 导出excel，不做鉴权
	 * 
	 * @return
	 */

	@RequestMapping(value = "export_DeviceInitList.json")
	@ResponseBody
	public Object exportDeviceInitList(String param) {
		boolean bln = checkRight();
		if (!bln) {
			toRedirect(404);
		}
		if (param == null) {
			param = "";
		}	
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			ArrayList<String> listParm = new ArrayList<String>();
			listParm.add(Constant.Device.DEVICE_TYPE);
			listParm.add(Constant.Device.FACTORY);
			listParm.add(Constant.Device.IMEI);
			listParm.add(Constant.Device.PUT_STATUS);
			listParm.add(Constant.Device.PUT_OBJECT);
			listParm.add(Constant.Device.BATCHID);
			listParm.add(Constant.Device.BOXID);
			List<List<String>> listValue = new LinkedList<List<String>>();
			// 限制最多导出4万条数据，前端可以通过细化查询条件来多次导出
			if (StringUtil.isBlank(paramForm.getPagecount())) {
				paramForm.setPagecount(Constant.Excel.EXPORT_ROWS);
			}
			PageModel<DeviceInfo> page = deviceInitService.queryDeviceInitlistPage(paramForm);
			List<DeviceInfo> list = page.getQueryresult();

			// 限制最多导出1万条数据，前端可以通过细化查询条件来多次导出
			for (int m = 0; m < list.size(); m++) {
				List<String> value = new LinkedList<String>();
				DeviceInfo deviceinfo = list.get(m);
				value.add(getDeviceTypename(deviceinfo.getDevicetype()));
				value.add(deviceinfo.getFactory());
				value.add(deviceinfo.getMdtid());
				value.add(getPayStatusName(deviceinfo.getPaystatus()!=null?deviceinfo.getPaystatus():-10));
				value.add(deviceinfo.getSchoolname());
				value.add(deviceinfo.getBatchid());
				value.add(deviceinfo.getBoxid());
				listValue.add(value);
				deviceinfo = null;
			}

			// 创建新的Excel 工作簿
			HSSFWorkbook workbook = exportDeviceList(Constant.Excel.DEVICE_EXCEL, listParm, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=deviceinitlist.xls");
			workbook.write(this.getResponse().getOutputStream());

		} catch (Exception e) {
			logger("DeviceInitManage exportDeviceInitList:"+e.getMessage(),e);
			toRedirect(500);
		}
		return success();

	}
	
	/**
	 * 
	 * <p>Title: exportTamplate</p>
	 * <p> 功能描述:导入excel模板下载 </p>
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "export_DeviceTamplate.json")
	@ResponseBody
	public Object exportTamplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook=null;
			List<List<String>> listValue = new LinkedList<List<String>>();
			listParm.add(Constant.Device.FACTORY);
			listParm.add(Constant.Device.IMEI);
			listParm.add(Constant.Device.FEE);
			listParm.add(Constant.Device.FEE2);
			listParm.add(Constant.Device.BATCHID);
			listParm.add(Constant.Device.BOXID);
			listParm.add(Constant.Device.CARDID);
			listParm.add(Constant.Device.DEVICEPACKAGE);
			listParm.add(Constant.Device.SCHOOL);
			listParm.add(Constant.Device.TELEPHONE);
			listExample.add(Constant.Excel.FACTORY_EXAMPLE);
			listExample.add("860705030025400");
			listExample.add("199");
			listExample.add("299");
			listExample.add(Constant.Excel.CARDID_BOXID_EXAMPLE);
			listExample.add(Constant.Excel.CARDID_BOXID_EXAMPLE);
			listExample.add("534687687");
			listExample.add("1年");
			listExample.add(Constant.Excel.SCHOOL_EXAMPLE);
			listExample.add("18988998899");
			listExample.add(Constant.Excel.WARNING);
			// 创建新的Excel 工作簿
			workbook = exportDeviceList(Constant.Excel.DEVICE_EXCEL, listParm,listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=importDeviceInitList.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("DeviceInitManage exportTamplate:"+e.getMessage(),e);
			toRedirect(500);
		}
		return success();

	}
	
	/**
	 * 
	 * <p>Title: ImportDevice</p>
	 * <p> 功能描述:导入excel到数据库 </p>
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/importDevice.json", method = RequestMethod.POST)
	@ResponseBody
	public Object importDevice(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		InputStream fileReport = null;
		try {
			fileReport=file.getInputStream();
			String fileName = file.getOriginalFilename();
			if (fileName.endsWith("xlsx")) {
				return fail(Constant.Excel.TYPE_IS_FALSE);
			}
			//把一张xls的数据表读到wb里
			HSSFWorkbook wb = new HSSFWorkbook(fileReport);
			String isImport=deviceInitService.importDevice(wb);
			if(Constant.Excel.IMPORT_TRUE.equals(isImport)){
				return success();
			}else{
				if (Constant.Excel.EXCEL_IS_EXIST.equals(isImport)) {
					//查询临时重复表
					return success(deviceInitService.queryDeviceRepeat());
				}else {
					return fail(isImport);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger("DeviceInitManage importDevice:"+e.getMessage(),e);
			if (e instanceof OpServiceException) {
				return fail(e);
			}
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}finally{
			try {
				fileReport.close();
			} catch (IOException e) {
				logger("DeviceInitManage importDevice:"+e.getMessage(),e);
			}
		}
	}

	
	/**
	 * 
	 * <p>Title: queryDeviceTmpList</p>
	 * <p> 功能描述:查询最近一次入库 </p>
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryDeviceTmpList.json")
	public Object queryDeviceTmpList(String param){
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			param="";
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			return success(deviceInitService.queryDeviceTmp(paramForm));
		} catch (Exception e) {
			logger("DeviceInitManage queryDeviceTmpList:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 
	 * <p>Title: cancel</p>
	 * <p> 功能描述:撤销导入数据库操作 </p>
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "cancelDeviceImport.json")
	public Object cancel(){
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			String isdeleted=deviceInitService.cancelDeviceImport();
			if(Constant.SUCCESS.equals(isdeleted)){
				return success(Constant.SUCCESS);
			}else{
				return fail(isdeleted);
			}
		}catch(Exception e) {
			logger("DeviceInitManage cancel:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 添加设备
	 * 
	 * @return
	 */

	@RequestMapping(value = "addDevice.json")
	@ResponseBody
	public Object addDevice(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm  device = new Gson().fromJson(param, ParamForm.class);
			if (device == null) {
				return fail(Constant.EMPTY);
			}
			String res = deviceInitService.addDevice(device);
			if (Constant.SUCCESS.equals(res)) {
				return success(Constant.OPERATE_SUCCESS);
			}else {
				return fail(res);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger("DeviceInitManage addDevice:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * 修改设备
	 * 
	 * @return
	 */

	@RequestMapping(value = "updateDevice.json")
	@ResponseBody
	public Object updateDevice(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm device = new Gson().fromJson(param, ParamForm.class);
			if (device == null || StringUtil.isBlank(device.getImei())) {
				return fail(Constant.EMPTY);
			}
			DeviceInfo temp = deviceInitService.queryDeviceByName(device);
			if (temp != null && !StringUtil.isBlank(temp.getImei()) && !String.valueOf(temp.getId()).equals(device.getId())) {
				String result = new StringBuffer().append(Constant.Device.DEVICE_IS_EXIST).append(temp.getImei()).toString();
				return fail(result);
			}
			int res = deviceInitService.updateDevice(device);

			if (res > 0) {
				return success(Constant.OPERATE_SUCCESS);
			}else {
				return fail(Constant.OPERATE_FAIL);
			}
		} catch (Exception e) {
			logger("DeviceInitManage updateDevice:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * 删除设备
	 * 
	 * @return
	 */

	@RequestMapping(value = "deleteDevice.json")
	@ResponseBody
	public Object deleteDevice(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			DeviceInfo device = new Gson().fromJson(param, DeviceInfo.class);
			if (device == null || device.getId()==null) {
				return fail(Constant.EMPTY);
			}
			DeviceInfo temp = deviceInitService.queryDeviceByID(device);
			if (temp == null ) {
				return fail(Constant.Device.DEVICE_IS_NOT_EXIST);
			}
			int res = deviceInitService.deleteDevice(device.getId());

			if (res > 0) {
				return success(Constant.OPERATE_SUCCESS);
			}else{
				return fail(Constant.OPERATE_FAIL);
			}
		} catch (Exception e) {
			logger("DeviceInitManage deleteDevice:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 设备投放
	 * 
	 * @return
	 */

	@RequestMapping(value = "putDevice.json")
	@ResponseBody
	public Object putDevice(String param) {
		boolean bln = checkRight();
		if (!bln)
			return fail(Constant.Authority.CHECK_FALSE);
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			DeviceInfo device = new Gson().fromJson(param, DeviceInfo.class);
			if (device == null || StringUtil.isBlank(device.getIds()) || device.getSchoolid()==null) {
				return fail(Constant.EMPTY);
			}
			device.setIds(device.getIds().replaceAll("\\|", ","));
			ParamForm paramForm=new ParamForm();
			paramForm.setSchoolid(device.getSchoolid().toString());
			School school=schoolService.querySchoolByID(paramForm);
			device.setSchoolname(school.getSchoolname());
			deviceInitService.putDevice(device);
			return success(Constant.OPERATE_SUCCESS);
		} catch (Exception e) {
			if (e instanceof OpServiceException) {
				return fail(e.getMessage());
			}
			logger("DeviceInitManage putDevice:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	/**
	 * 
	 * <p>Title: queryAllDeviceRows</p>
	 * <p> 功能描述:查询所有设备个数 </p>
	 * @return
	 */
	@RequestMapping(value = "/countAllDevice.json")
	@ResponseBody
	public Object queryAllDeviceRows(){
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			Map<String,Object> result = new HashMap<>();
			result.put("devicerows", deviceInitService.queryAllDeviceRows());
			return success(result);
		}catch (Exception e) {
			logger("DeviceInitManage queryAllDeviceRows:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	
	/**
	 * 
	 * <p>Title: exportTamplate</p>
	 * <p> 功能描述:导入excel模板下载 </p>
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/export_DeviceReserveTemplate.json")
	@ResponseBody
	public Object exportDeviceReserveTemplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook=null;
			List<List<String>> listValue = new LinkedList<List<String>>();
			listParm.add(Constant.Device.DEVICETYPE);
			listParm.add(Constant.Device.CARDID);
			listExample.add("13.56/2.4");
			listExample.add("534687687");
			listExample.add(Constant.Excel.WARNING);
			// 创建新的Excel 工作簿
			workbook = exportDeviceList(Constant.Excel.RESERVE_EXCEL, listParm,listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=deviceReserveTemplate.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("DeviceInitManage exportDeviceReserveTemplate:"+e.getMessage(),e);
			toRedirect(500);
		}
		return success();

	}
	
	/**
	 * 
	 * <p>Title: queryAllDeviceRows</p>
	 * <p> 功能描述:新增储备量 </p>
	 * @return
	 */
	@RequestMapping(value = "/addDeviceReserve.json", method = RequestMethod.POST)
	@ResponseBody
	public Object addDeviceReserve(@RequestParam("file") MultipartFile file,HttpServletRequest request,String param){
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		InputStream fileReport = null;
		try {
			if (com.suixun.util.StringUtil.isEmpty(param)) {
				return fail(Constant.Device.REGION_NOT_NULL);
			}
			DeviceVO deviceVo = new Gson().fromJson(param, DeviceVO.class);
			fileReport=file.getInputStream();
			String fileName = file.getOriginalFilename();
			if (fileName.endsWith("xlsx")) {
				return fail(Constant.Excel.TYPE_IS_FALSE);
			}
			//把一张xls的数据表读到wb里
			HSSFWorkbook wb = new HSSFWorkbook(fileReport);
			Object isImport=deviceInitService.importDeviceReserve(wb,deviceVo);
			if (isImport instanceof String) {
				String res = (String)isImport;
				if (Constant.SUCCESS.equals(res)) {
					return success();
				}else{
					return fail(res);
				}
			}else {
				return success(isImport);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger("DeviceInitManage addDeviceReserve:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}finally{
			try {
				fileReport.close();
			} catch (IOException e) {
				logger("DeviceInitManage addDeviceReserve:"+e.getMessage(),e);
			}
		}
	}
	
	/**
	 * 
	 * <p>Title: queryAllDeviceRows</p>
	 * <p> 功能描述:设备投放 </p>
	 * @return
	 */
	@RequestMapping(value = "/putDeviceReserve.json")
	@ResponseBody
	public Object putDeviceReserve(String param){
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			if (com.suixun.util.StringUtil.isEmpty(param)) {
				return fail(Constant.EMPTY);
			}
			DeviceVO device = new Gson().fromJson(param, DeviceVO.class);
			if (device == null || com.suixun.util.StringUtil.isEmpty(device.getSchoolid())) {
				return fail(Constant.Device.SCHOOL_NOT_NULL);
			}
			if (com.suixun.util.StringUtil.isEmpty(device.getIds())) {
				return fail(Constant.Device.DEVICEID_NOT_NULL);
			}
			if (com.suixun.util.StringUtil.isEmpty(device.getProvince())
			   || com.suixun.util.StringUtil.isEmpty(device.getCity())
			   || com.suixun.util.StringUtil.isEmpty(device.getTown())) {
				return fail(Constant.Device.REGION_NOT_NULL);
			}
			String res = deviceInitService.putDeviceReserve(device);
			if (Constant.SUCCESS.equals(res)) {
				return success();
			}else {
				return fail(res);
			}
		}catch (Exception e) {
			e.printStackTrace();
			logger("DeviceInitManage putDeviceReserve:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 
	 * <p>Title: queryAllDeviceRows</p>
	 * <p> 功能描述:区域储备量统计 </p>
	 * @return
	 */
	@RequestMapping(value = "/getDeviceReserveCount.json")
	@ResponseBody
	public Object getDeviceReserveCount(String param){
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			DeviceVO device = null;
			if (com.suixun.util.StringUtil.isEmpty(param)) {
				device = new DeviceVO();
			}else {
				device = new Gson().fromJson(param, DeviceVO.class);
			}
			return success(deviceInitService.getDeviceReserveCount(device));
		}catch (Exception e) {
			e.printStackTrace();
			logger("DeviceInitManage getDeviceReserveCount:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 
	 * <p>Title: queryAllDeviceRows</p>
	 * <p> 功能描述:区域储备量详情 </p>
	 * @return
	 */
	@RequestMapping(value = "/getDeviceReserves.json")
	@ResponseBody
	public Object getDeviceReserves(String param){
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			DeviceVO device = null;
			if (com.suixun.util.StringUtil.isEmpty(param)) {
				device = new DeviceVO();
			}else {
				device = new Gson().fromJson(param, DeviceVO.class);
			}
			if (device == null) {
				return fail(Constant.EMPTY);
			}else {
				if (device.getIslast() == null) {
					if (com.suixun.util.StringUtil.isEmpty(device.getProvince())
							   || com.suixun.util.StringUtil.isEmpty(device.getCity())
							   || com.suixun.util.StringUtil.isEmpty(device.getTown())) {
						return fail(Constant.Device.REGION_NOT_NULL);
					}
					if (com.suixun.util.StringUtil.isEmpty(device.getDevicetype())) {
						return fail(Constant.Device.DEVICETYPE_NOT_NULL);
					}
				}
			}
			return success(deviceInitService.getDeviceReserves(device));
		}catch (Exception e) {
			logger("DeviceInitManage getDeviceReserves:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	
	/**
	 * 
	 * <p>Title: cancelDeviceReserve</p>
	 * <p> 功能描述:撤销最后一次入库</p>
	 * @return
	 */
	@RequestMapping(value = "/cancelDeviceReserve.json")
	@ResponseBody
	public Object cancelDeviceReserve(String param){
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			String isdeleted=deviceInitService.cancelLastImport();
			if(Constant.SUCCESS.equals(isdeleted)){
				return success();
			}else{
				return fail(isdeleted);
			}
		}catch(Exception e) {
			e.printStackTrace();
			logger("DeviceInitManage cancelDeviceReserve:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 回收设备
	 * 
	 * @return
	 */

	@RequestMapping(value = "recycleDevice.json")
	@ResponseBody
	public Object recycleDevice(String param) {
		try {
			ParamForm paramForm = checkParam(param, ParamForm.class);
			deviceInitService.recycleDevice(paramForm);
			return success();
		} catch (Exception e) {
			if (e instanceof OpServiceException) {
				return fail(e.getMessage());
			}
			e.printStackTrace();
			logger("DeviceInitManage recycleDevice:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
}
